package com.mimosa.common.system.role;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.mimosa.common.dao.HibernateDao;

@Repository
public class TUserRoleDao extends HibernateDao<TUserRole, String> {
	/**
	 * 根据角色id删除角色用户表中的所有对象
	 * 
	 * @param roleId
	 */
	public void deleteUserFromRole(String roleId, String[] userIds) {
		TUserRole queryObj = null;
		for (String userId : userIds) {
			queryObj = this.findUnique("from TUserRole u where u.roleId = ? and u.userId=?", roleId, userId);
			if (queryObj != null) {
				this.delete(queryObj);
			}
		}
	}

	/**
	 * 根据用户的主键删除与角色的关联信息
	 * 
	 * @param userId
	 */
	public void deleteByUserId(String userId) {
		List<TUserRole> userRoleList = this.findBy("userId", userId);
		for (TUserRole userRole : userRoleList) {
			this.delete(userRole);
		}
	}

	/**
	 * 根据角色的主键删除与用户的关联信息
	 * 
	 * @param userId
	 */
	public void deleteByRoleId(String roleId) {
		List<TUserRole> userRoleList = this.findBy("roleId", roleId);
		for (TUserRole userRole : userRoleList) {
			this.delete(userRole);
		}
	}

	/**
	 * 建立人到角色之间的关联
	 * 
	 * @param userId
	 * @param roleids
	 */
	public void saveUser2Role(String roleId, String[] userIds) {
		TUserRole queryObj = null;
		for (String userId : userIds) {
			queryObj = this.findUnique("from TUserRole t where t.userId = ? and t.roleId=?", userId, roleId);
			if (queryObj == null) {
				queryObj = new TUserRole();
				queryObj.setRoleId(roleId);
				queryObj.setUserId(userId);
				super.save(queryObj);
			}
		}
	}
}